package com.lfz.quality_effect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lfz.quality_effect.exception.MyException;
import com.lfz.quality_effect.model.dto.DeliveryRateDTO;
import com.lfz.quality_effect.model.entity.TDeliveryStatistics;
import com.lfz.quality_effect.mapper.TDeliveryStatisticsMapper;
import com.lfz.quality_effect.model.vo.TDeliveryStatisticsVO;
import com.lfz.quality_effect.service.TDeliveryStatisticsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfz.quality_effect.utils.ReturnCode;
import com.lfz.quality_effect.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 电子送达统计信息 服务实现类
 * </p>
 *
 * @author Destiny
 * @since 2023-03-21
 */
@Service
public class TDeliveryStatisticsServiceImpl extends ServiceImpl<TDeliveryStatisticsMapper, TDeliveryStatistics> implements TDeliveryStatisticsService {
    /**
     * 格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
    @Override
    public void uploadDelivertStatistics(DeliveryRateDTO deliveryRateDTO) {
        String court = deliveryRateDTO.getCourt();
        String dataTime = deliveryRateDTO.getDataTime();
      BigDecimal delivertRate = deliveryRateDTO.getDeliveryRate();
       Integer caseTotal = deliveryRateDTO.getCaseTotal();
       Integer deliveredTotal = deliveryRateDTO.getDeliveredTotal();
        //日期校验
        try {
            dataTime = simpleDateFormat.format(TimeUtils.vertifyTime(dataTime));
        }catch (Exception e){
            throw new MyException(ReturnCode.RC10002.getCode(),ReturnCode.RC10002.getMsg());
        }
     TDeliveryStatistics deliveryStatistics =   this.getOne(new LambdaQueryWrapper<TDeliveryStatistics>()
                .eq(TDeliveryStatistics::getDataTime,dataTime)
                .eq(TDeliveryStatistics::getCourt,court));
        if (deliveryStatistics == null){
            deliveryStatistics = new TDeliveryStatistics();
            deliveryStatistics.setDeliveryRate(delivertRate);
            deliveryStatistics.setCourt(court);
            deliveryStatistics.setCreateTime(LocalDateTime.now());
            deliveryStatistics.setCaseTotal(caseTotal);
            deliveryStatistics.setDeliveredTotal(deliveredTotal);
            deliveryStatistics.setNotDeliveryTotal(caseTotal-deliveredTotal);
            deliveryStatistics.setDataTime(dataTime);
            this.save(deliveryStatistics);
        }
    }

    /**
     * 电子送达率——优化
     * @return
     */
    @Override
    public TDeliveryStatisticsVO optimizeDelivertStatistics() {
       return this.getBaseMapper().optimizeDelivertStatistics();
    }
}
